# coding: utf-8
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from common.overwrites import z_render_to_response
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from common.models.game import Game, GamePlayTrace
from django.conf import settings
from common.services.logic import LogicService


@csrf_exempt
def game_list(request):
    games = Game.objects.all()
    for g in games:
        g.tops = GamePlayTrace.objects.order_by('-score')[:10]
    return z_render_to_response('game/game_list.html', {'games': games})


@login_required
@csrf_exempt
def game_detail(request):
    if request.method == 'GET':
        game = Game.objects.get(id=int(request.GET.get('game_id')))
        return z_render_to_response(game.template, {'game': game})


@login_required
@csrf_exempt
def submit_score(request):
    if request.method == 'POST':
        game = Game.objects.get(id=int(request.POST.get('game_id')))
        score = request.POST.get('score')

        LogicService.submit_game_score(request.user.id, game.id, score)
        return JsonResponse({'success': True})